package org.example.weboj.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.weboj.dto.AIChatRequest;
import org.example.weboj.service.AIStreamChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;

/**
 * AI流式聊天WebSocket处理器
 */
@Component
public class AIStreamWebSocketHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(AIStreamWebSocketHandler.class);
    private final ObjectMapper objectMapper;
    private final AIStreamChatService aiStreamChatService;

    @Autowired
    public AIStreamWebSocketHandler(ObjectMapper objectMapper, AIStreamChatService aiStreamChatService) {
        this.objectMapper = objectMapper;
        this.aiStreamChatService = aiStreamChatService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        logger.info("AI聊天WebSocket连接已建立: {}", session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        logger.info("收到WebSocket消息: {}", payload);

        try {
            // 解析客户端发送的聊天请求
            AIChatRequest chatRequest = objectMapper.readValue(payload, AIChatRequest.class);

            // 启动流式聊天
            aiStreamChatService.streamChat(chatRequest, session);
        } catch (Exception e) {
            logger.error("处理WebSocket消息时出错", e);
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(
                Map.of(
                    "success", false,
                    "error", "处理请求时出错: " + e.getMessage(),
                    "done", true
                )
            )));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        logger.info("AI聊天WebSocket连接已关闭: {}, 状态: {}", session.getId(), status);
    }
}
